var setting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "menuId",
			pIdKey: "parentId",
			rootPId: -1
		},
		key: {
			url:"nourl"
		}
	},
	check:{
		enable:true,
		nocheckInherit:true
	}
};
var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			roleName: null
		},
		showList: true,
		title:null,
		role:{},
		menuList:store.get('menuList'),
		permissions:store.get('permissions'),
		username:store.get('user').username,
		password:'',
		newPassword:''
	},
	methods: {
		query: function () {
			var layer_index = layer.load(0, {shade: false});
			this.reload();
			layer.close(layer_index);
		},
		add: function(){
			this.showList = false;
			this.title = "新增";
			this.role = {};
			this.getMenuTree(null);
		},
		update: function () {
			var roleId = this.getSelectedRow();
			if(roleId == null){
				return ;
			}
			
			this.showList = false;
			this.title = "修改";
			this.getMenuTree(roleId);
		},
		del: function () {
			var roleIds = this.getSelectedRows();
			if(roleIds == null){
				return ;
			}
			
			layer.confirm('确定要删除选中的记录？', function(){
				var layer_index;
				$.ajax({
					type: "POST",
				    url: "../sys/role/delete",
				    data: JSON.stringify(roleIds),
				    beforeSend:function(){
				    	layer_index = layer.load(0, {shade: false});
				    },
				    success: function(r){
				    	layer.close(layer_index);
						if(r.code == 0){
							layer.alert('操作成功', function(index){
								vm.reload();
							});
						}else{
							layer.alert(r.msg);
						}
					}
				});
			});
		},
		getRole: function(roleId){
            $.get("../sys/role/info/"+roleId, function(r){
            	vm.role = r.role;
                
                //勾选角色所拥有的菜单
    			var menuIds = vm.role.menuIdList;
    			for(var i=0; i<menuIds.length; i++) {
    				var node = ztree.getNodeByParam("menuId", menuIds[i]);
    				ztree.checkNode(node, true, false);
    			}
    		});
		},
		saveOrUpdate: function (event) {
			//获取选择的菜单
			var nodes = ztree.getCheckedNodes(true);
			if(nodes == null || nodes.length == 0){
				layer.alert('请选择菜单', {
					  icon: 5
					});
				return false;
			}
			var menuIdList = [];
			for(var i=0; i<nodes.length; i++) {
				menuIdList.push(nodes[i].menuId);
			}
			this.role.menuIdList = menuIdList;
			
			var url = this.role.roleId == null ? "../sys/role/save" : "../sys/role/update";
			var layer_index;
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.role),
			    beforeSend:function(){
			    	layer_index = layer.load(0, {shade: false});
			    },
			    success: function(r){
			    	layer.close(layer_index);
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				},
				error: function(){
					layer.close(layer_index);
					layer.alert('操作失败');
				}
			});
		},
		getMenuTree: function(roleId) {
			//加载菜单树
			$.get("../sys/menu/perms", function(r){
				ztree = $.fn.zTree.init($("#menuTree"), setting, r.menuList);
				//展开所有节点
				ztree.expandAll(true);
				
				if(roleId != null){
					vm.getRole(roleId);
				}
			});
	    },
		reload: function (event) {
			this.showList = true;
			var dom_jqGrid = $("#jqGrid");
			var page = dom_jqGrid.jqGrid('getGridParam','page');
			dom_jqGrid.jqGrid('setGridParam',{ 
				postData:{'roleName': vm.q.roleName},
                page:page
            }).trigger("reloadGrid");
		},
		updatePassword: function(){
			layer.open({
				type: 1,
				skin: 'layui-layer-molv',
				title: "修改密码",
				area: ['550px', '270px'],
				shadeClose: false,
				content: $("#passwordLayer"),
				btn: ['修改','取消'],
				btn1: function (index) {
					if(vm.password ==''){
						layer.close(index);
						layer.alert('原密码不能为空', {
							  icon: 5
							});
						return false;
					}
					if(vm.newPassword == ''){
						layer.close(index);
						layer.alert('新密码不能为空', {
							  icon: 5
							});
						return false;
					}
					var data = "password="+vm.password+"&newPassword="+vm.newPassword;
					$.ajax({
						type: "POST",
					    url: "sys/user/password",
					    data: data,
					    dataType: "json",
					    success: function(result){
							if(result.code == 0){
								layer.close(index);
								layer.alert('修改成功', function(index){
									location.reload();
								});
							}else{
								layer.alert(result.msg);
							}
						}
					});
	            }
			});
		},
		doLogout:function(){
			$.getJSON("/sys/logout?_"+$.now(), function(r){
				store.remove('menuList');
				store.remove('permissions');
				store.remove('user');
				this.user = {};
				this.menuList = {};
				this.permissions = {};
				location.href='login.html';
			});
		},
		hasPermission:function(permission){
			if(this.permissions.indexOf(permission) > -1){
				return true;
			}else{
				return false;
			}
		},
		getSelectedRow:function(){
			var grid = $("#jqGrid");
		    var rowKey = grid.getGridParam("selrow");
		    if(!rowKey){
		    	layer.alert("请选择一条记录");
		    	return ;
		    }
		    
		    var selectedIDs = grid.getGridParam("selarrrow");
		    if(selectedIDs.length > 1){
		    	layer.alert("只能选择一条记录");
		    	return ;
		    }
		    
		    return selectedIDs[0];
		},
		getSelectedRows:function(){
			var grid = $("#jqGrid");
		    var rowKey = grid.getGridParam("selrow");
		    if(!rowKey){
		    	layer.alert("请选择一条记录");
		    	return ;
		    }
		    
		    return grid.getGridParam("selarrrow");
		}
	}
});

$(function () {
	$.jgrid.defaults.width = 1000;
	$.jgrid.defaults.responsive = true;
	$.jgrid.defaults.styleUI = 'Bootstrap';
	
	var $jqGrid =  $("#jqGrid");
	$jqGrid.jqGrid({
        url: '../sys/role/list',
        datatype: "json",
        colModel: [			
			{ label: '角色ID', name: 'roleId', index: "role_id", width: 45, key: true },
			{ label: '角色名称', name: 'roleName', index: "role_name", width: 75 },
			{ label: '备注', name: 'remark', width: 100 },
			{ label: '创建时间', name: 'createTime', index: "create_time", width: 80}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$jqGrid.closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});